package database;

import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;

public class PostgreSqlDemo {
    public static void main(String[] args) throws SQLException, IOException {
        try(Connection connection = getConnection();
            Statement statement = connection.createStatement()) {
            statement.executeUpdate("create table Greetings (Message varchar(50))");
            statement.executeUpdate("insert into Greetings values('hello postgresql')");

            try(ResultSet rs = statement.executeQuery("select * from Greetings")) {
                if (rs.next()) {
                    System.out.println(rs.getString(1));
                }
            }
            statement.executeUpdate("drop table Greetings");
        }
    }

    public static Connection getConnection() throws IOException, SQLException {
        Properties prop = new Properties();
        try(InputStream in = Files.newInputStream(Paths.get("database.properties"))) {
            prop.load(in);
        }
        String drivers = prop.getProperty("jdbc.drivers");
        if (drivers != null) {
            System.setProperty("jdbc.drivers", drivers);
        }
        String url = prop.getProperty("jdbc.url");
        String username = prop.getProperty("jdbc.username");
        String password = prop.getProperty("jdbc.password");

        return DriverManager.getConnection(url, username, password);
    }
}
